﻿using Microsoft.Extensions.Hosting;
using Serilog;
using StudentInfoSystem.Core.Interfaces;
using StudentInfoSystem.Core.Models;
using System.ComponentModel;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Extensions.DependencyInjection;

namespace StudentInfoSystem.UI.Services;

/// <summary>
/// 自动保存服务
/// 控制学生数据的存储
/// </summary>
public class AutoSaveService : IHostedService, IDisposable
{
    private readonly AppSettings _settings;
    private readonly IServiceProvider _serviceProvider;
    private Timer? _timer;
    private bool _disposed;

    public AutoSaveService(AppSettings settings, IServiceProvider serviceProvider)
    {
        _settings = settings;
        _serviceProvider = serviceProvider;

        // 订阅设置更改事件
        _settings.PropertyChanged += OnSettingsChanged;
    }

    public Task StartAsync(CancellationToken cancellationToken)
    {
        Log.Information("自动保存服务启动");
        // 首次延迟 5 秒，确保初始化完成
        _timer = new Timer(SaveCallback, null,
            TimeSpan.FromSeconds(5),
            TimeSpan.FromMinutes(_settings.SaveInterval));
        return Task.CompletedTask;
    }

    public Task StopAsync(CancellationToken cancellationToken)
    {
        _timer?.Change(Timeout.Infinite, 0);
        Log.Information("自动保存服务已停止");

        Log.Debug("立即保存数据...");
        SaveCallback(null);
        return Task.CompletedTask;
    }

    private void OnSettingsChanged(object? sender, PropertyChangedEventArgs e)
    {
        if (e.PropertyName == nameof(AppSettings.AutoSaveEnabled) ||
            e.PropertyName == nameof(AppSettings.SaveInterval))
        {
            Log.Debug("设置变更: {PropertyName}", e.PropertyName);
            SetupTimer();
        }
    }

    private void SetupTimer()
    {
        Log.Debug("重新配置自动保存定时器");
        _timer?.Dispose();

        if (_settings.AutoSaveEnabled)
        {
            Log.Information("启动自动保存定时器, 间隔: {Interval}分钟", _settings.SaveInterval);
            _timer = new Timer(SaveCallback, null,
                TimeSpan.Zero,
                TimeSpan.FromMinutes(_settings.SaveInterval));
        }
        else
        {
            Log.Information("自动保存功能已禁用");
        }
    }

    private void SaveCallback(object? state)
    {
        Log.Debug("开始自动保存数据...");
        try
        {
            using (var scope = _serviceProvider.CreateScope())
            {
                var studentService = scope.ServiceProvider.GetRequiredService<IStudentService>();
                studentService.SaveStudents(); // 直接保存，无需先查询
            }
            Log.Information("学生数据保存成功");
        }
        catch (Exception ex)
        {
            Log.Error(ex, "保存数据时发生错误");
        }
    }

    public void Dispose()
    {
        if (!_disposed)
        {
            _timer?.Dispose();
            _settings.PropertyChanged -= OnSettingsChanged;
            _disposed = true;
            Log.Information("自动保存服务已释放");
        }
    }
}